//路由器的配置文件

//1、安装

//2、 引入并声明使用
import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
import store from '@/store'
Vue.use(VueRouter) //声明使用插件，所有的vue官方插件都要声明使用，第三方插件不需要
// 本质在调用插件内部的install方法，只有调用它，插件的功能才会添加到Vue身上和Vm身上
//3 、必须往外暴露一个路由器对象



const originPush = VueRouter.prototype.push  //把原本的push函数地址存起来，防止后面要用
const originReplace= VueRouter.prototype.replace  //把原本的push函数地址存起来，防止后面要用

//把今后使用的push改成我们自己定义的函数
VueRouter.prototype.push = function(location,resolved,rejected){
  if(resolved === undefined && rejected === undefined){
    return originPush.call(this,location).catch(() => {})
  }else{
    return originPush.call(this,location,resolved,rejected)
  }
}
VueRouter.prototype.replace = function(location,resolved,rejected){
  if(resolved === undefined && rejected === undefined){
    return originReplace.call(this,location).catch(() => {})
  }else{
    return originReplace.call(this,location,resolved,rejected)
  }
}

const router = new VueRouter({
  mode:'history',
  routes,
  scrollBehavior (to, from, savedPosition) {
    return { y: 0 }
  }
})

//配置全局前置路由导航守卫,进行token验证
router.beforeEach(async (to,from,next) => {
    let token = store.state.user.token
    let userInfo = store.state.user.userInfo
 
  // 判断是否是登陆状态
    if(token){
      //  判断是否是跳往的是登录页
      if(to.path == '/login'){
         next('/')
      }else{
        if(userInfo.name){
           next()
        }else{
           try {
              await store.dispatch('getUserInfo')
              next({...to})
           } catch (error) {
              // 进入这里证明token过期
              next('/login')
           }
        }
      }

    }else{
      let targetPath = to.path
      if(targetPath.indexOf('/shopcart')==0 || targetPath.startsWith('/pay') || targetPath.startsWith('/paysuccess') || targetPath.startsWith('/order')){
        next('/login?redirect='+targetPath)
      }else{
          next()  
      }
      
    }
})


export default  router

// localStorage.setItem('xxxx',obj)
//4、 必须在Vue的配置对象当中注册路由器对象
